package com.example.common.netty;

import com.example.common.converter.MsgTypeParser;
import com.example.common.util.HexStringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j(topic = "netty.handler")
@ChannelHandler.Sharable
public class HandlerNetty extends ChannelInboundHandlerAdapter {

    /**
     * 客户端发送消息会触发
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof ByteBuf) {
            final ByteBuf buf = (ByteBuf) msg;
            if (buf.readableBytes() <= 0) {
                return;
            }
            log.info("msg: {}",msg);
            final byte[] unescaped = new byte[buf.readableBytes()];
            buf.readBytes(unescaped);
            log.info("receive>>>>:{}", HexStringUtils.bytes2HexString(unescaped));
            System.out.println("---");
        }else{
            ctx.fireChannelRead(msg);
        }
    }
}
